#include <glib.h>

typedef struct mydata_tag {
  int id;
  char *name;
}my_data_t;

void my_struct_free_func(gpointer data)
{
    my_data_t *mydata = NULL;
    mydata = (my_data_t *)data;

    if(NULL != mydata->name) {
        //g_print("free mydata->name: %s \n", mydata->name);
        free(mydata->name);
    }

    return;
}

void my_struct_printf(gpointer data, gpointer user_data)
{
  g_printf("%s: id=%d, name=%s, user_data=%s\n", __FUNCTION__, 
    ((my_data_t *)data)->id, ((my_data_t *)data)->name, (char *)user_data);
}

gint my_cmp_func(gconstpointer  a, gconstpointer  b)
{
    my_data_t *node = NULL;

    node = (my_data_t *)a;

    //g_print("node->name: %s, b %s \n", node->name, (gchar *)b);
    return strcmp(node->name, b);
}

static void test_slist_find_custom_cmp(void)
{
    int i = 0;
    GSList *slist = NULL;
    GSList *slink = NULL;
    my_data_t *snode = NULL;
    my_data_t mydata[16];
    char name[16] = {0};

    memset(mydata, 0, sizeof(my_data_t)*5);
    for(i=0;i<5;i++) {
        mydata[i].id = i;
        g_snprintf(name, 16, "data is %d", i);
        mydata[i].name = strdup(name);
        slist = g_slist_append(slist,  (gpointer)&mydata[i]);
    }

    g_print("\n");
    g_print("len=%d \n", g_slist_length(slist));
    g_slist_foreach(slist, my_struct_printf, "my_struct_printf");
    slink = g_slist_nth(slist, 3);
    g_print("slink->data->id=%d \n", ((my_data_t *)slink->data)->id);

    snode = g_slist_nth_data(slist, 3);
    g_print("snode->id=%d \n", snode->id);

    slink = g_slist_find_custom(slist, "data is 3", my_cmp_func);
    if(NULL == slink) {
        g_print("data not found! \n");
    } else {
        g_print("found! %s \n", ((my_data_t *)(slink->data))->name);
    }

    g_slist_free_full(slist, my_struct_free_func);
}

gint main (gint argc, gchar *argv[])
{
    g_test_init (&argc, &argv, NULL);

    g_test_add_func ("/slist/find_custom_cmp", test_slist_find_custom_cmp);

    return g_test_run ();
}